package com.micro.ai.models.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.models.entity.ModelVersion;
import com.micro.ai.models.mapper.ModelVersionMapper;
import com.micro.ai.models.service.ModelVersionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 模型版本服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class ModelVersionServiceImpl extends ServiceImpl<ModelVersionMapper, ModelVersion> implements ModelVersionService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ModelVersion create(ModelVersion version) {
        if (version == null) {
            throw new BusinessException("M0000", "模型版本信息不能为空");
        }
        
        boolean success = this.save(version);
        if (!success) {
            throw new BusinessException("M0003", "保存模型版本失败");
        }
        
        log.info("创建模型版本成功: versionId={}, versionName={}", version.getId(), version.getVersionName());
        return version;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setCurrent(String id) {
        if (id == null) {
            throw new BusinessException("M0000", "版本ID不能为空");
        }
        
        ModelVersion version = this.getById(id);
        if (version == null) {
            throw new BusinessException("M0002", "模型版本不存在: " + id);
        }
        
        // 取消同模型下的所有当前版本标记
        LambdaQueryWrapper<ModelVersion> query = new LambdaQueryWrapper<>();
        query.eq(ModelVersion::getModelId, version.getModelId())
             .eq(ModelVersion::getIsCurrent, true)
             .ne(ModelVersion::getId, id);
        this.list(query).forEach(v -> {
            v.setIsCurrent(false);
            this.updateById(v);
        });
        
        // 设置当前版本
        version.setIsCurrent(true);
        boolean success = this.updateById(version);
        if (!success) {
            throw new BusinessException("M0003", "设置当前版本失败");
        }
        
        log.info("设置当前版本成功: versionId={}, modelId={}", id, version.getModelId());
    }

    @Override
    public Page<ModelVersion> listByModelId(String modelId) {
        LambdaQueryWrapper<ModelVersion> query = new LambdaQueryWrapper<>();
        query.eq(ModelVersion::getModelId, modelId)
             .orderByDesc(ModelVersion::getCreatedAt);
        
        return this.page(new Page<>(1, 100), query);
    }
}

